package cn.com.dcsgo.interceptor;

import cn.com.dcsgo.common.Result;
import cn.com.dcsgo.constants.CoreConstant;
import cn.com.dcsgo.enums.ResultEnums;
import cn.com.dcsgo.utils.ServletUtils;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.io.Serializable;

/**
 * 登录拦截器，处理所有未登录的请求
 *
 * @author Dcsgo
 * @since 21/5/2025 下午 3:29
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // session 中有用户信息即为已登录
        Object user = ServletUtils.getSession().getAttribute(CoreConstant.SESSION_KEY);
        if (user != null) {
            log.debug("登录拦截器放行请求");
            return true;
        }
        // 没有用户信息，未登录，使用 response 返回提示信息
        Result<Serializable> result = new Result<>(ResultEnums.USER_NOT_LOGIN);
        String resultJson = JSON.toJSONString(result);
        log.debug("登录拦截器拦截请求,响应数据:{}", resultJson);

        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");
        
        PrintWriter writer = response.getWriter();
        writer.write(resultJson);
        writer.flush();
        writer.close();

        return false;
    }
}
